<template>
  <div class="filter-detail">
    <BasicCard>
      <!-- <BasicVxeForm ref="formRef" :formOptions="formOptions"></BasicVxeForm> -->
      <BasicVxeTable v-bind="gridOptions">
        <template #stateCode="{ row }">
          <div class="flex flex-center-justify" style="width: 100%">
            <el-tag effect="dark" style="margin-top: 4px" :color="zhuanTai.color(row.stateCode)">
              {{ zhuanTai.text(row.stateCode, processName) }}
            </el-tag>
          </div>
        </template>
      </BasicVxeTable>
    </BasicCard>
    <BasicCard class="chart-card">
      <BasicTitle :title="t('custom.趋势分析')"></BasicTitle>
      <div class="filter-div">
        <div class="time-item">
          <el-button :icon="ArrowLeft" @click="handleChangeTime('sub')">前12小时</el-button>
          <el-button @click="handleChangeTime('add')">
            后12小时<el-icon class="el-icon--right"><ArrowRight /> </el-icon>
          </el-button>
        </div>
        <div class="type-item">
          <el-select v-model="selectCode" style="width: 240px" @change="getChartData">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            /> </el-select
        ></div>
      </div>
      <div id="zheXianID" style="height: 400px"></div>
    </BasicCard>
  </div>
</template>
<script setup lang="ts">
  import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
  import { FilterDetailTableColumns } from '../../data'
  import { postGongXuXiaLiShiQuShiTu, postShiSiXinXinList_qingHua } from '@/api/shengChanJianShi'
  import { getLuoTongZhiJiJiTaiTheGongYi } from '@/api/gongGongChaXun'
  import dayjs from 'dayjs'
  import * as echarts from 'echarts'
  import { hexToRgba, zhuanTai } from '@/utils/custom'

  const props = defineProps<{
    processName: string
    statusCode: string
  }>()

  const { t } = useI18n()
  const machineList = ref<any>([])
  const machineIdArr = ref<any>([])
  const machineId = ref()
  const machineStr = ref()
  let optionsList = reactive([])

  const formOptions = reactive<BasicFormProps<any>>({
    data: {
      pageType: 'material'
    },
    items: [
      {
        field: 'equipment',
        title: '',
        // span: 8,
        visible: true,
        itemRender: {
          name: 'SelectModal',
          props: {
            modalConfig: {
              title: t('system.机台列表', { name: t('custom.滤尘') }),
              options: optionsList
            }
          }
        }
      },
      {
        align: 'center',
        span: 2,
        itemRender: {
          name: 'ElButtons',
          children: [
            {
              type: 'primary',
              content: t('system.查询'),
              events: {
                click: (params) => {
                  console.log(params)
                  // handleSearch(params)
                }
              }
            }
          ]
        }
      }
    ]
  })

  const gridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: t('custom.机台报表'),
      isCustom: true,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `filter-detail-${props.statusCode}`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    maxHeight: 480,
    exportConfig: {
      filename: '滤尘机台报表'
    },
    columns: FilterDetailTableColumns
  })

  // 获取气表list数据
  const getMachineList = () => {
    getLuoTongZhiJiJiTaiTheGongYi('滤尘').then((res: any) => {
      res.sort((a, b) => {
        return a.machineNo - b.machineNo
      })
      machineList.value = res.map((value) => {
        return {
          id: value.id,
          name: value.machineName,
          value: value.id,
          label: value.machineName,
          machineNo: value.machineNo,
          craftNodeName: value.craftNodeName
        }
      })

      optionsList = machineList.value
      machineIdArr.value = machineList.value.map((val) => {
        return val.id
      })
      getMachineReportList()
    })
  }

  const getMachineReportList = () => {
    postShiSiXinXinList_qingHua(machineIdArr.value).then((res: any) => {
      let arr = res.map((value) => {
        if (value.machineRealInfo != null) {
          return {
            gongXu: '滤尘',
            machineName: value.basic.machineName,
            machineNo: value.basic.machineNo,
            machineDocumentId: value.basic.machineDocumentId,
            stateCode: value.basic.stateCode,
            S11001: value.machineRealInfo.realtime.S11001,
            S11002:
              value.machineRealInfo.realtime.S11002 == null
                ? null
                : Math.round(value.machineRealInfo.realtime.S11002 * 100) / 100,
            S11003:
              value.machineRealInfo.realtime.S11003 == null
                ? null
                : Math.round(value.machineRealInfo.realtime.S11003 * 100) / 100,
            S11004:
              value.machineRealInfo.realtime.S11004 == null
                ? null
                : Math.round(value.machineRealInfo.realtime.S11004 * 100) / 100
          }
        } else {
          return {
            name: value.basic.machineDisplayState
          }
        }
      })
      arr.sort((a, b) => {
        return a.machineNo - b.machineNo
      })
      gridOptions.data = arr
      machineId.value = arr[0].machineDocumentId
      machineStr.value = arr[0].machineName
      startTime.value = dayjs().subtract(12, 'hour').format('YYYY-MM-DD HH:mm:ss')
      endTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
      getChartData()
    })
  }

  const handleChangeTime = (val) => {
    console.log(val)
    if (val == 'add') {
      startTime.value = endTime.value
      endTime.value = dayjs(endTime.value).add(12, 'hour').format('YYYY-MM-DD HH:mm:ss')
      timeBool.value = dayjs(constantTime.value).isAfter(dayjs(endTime.value))
    } else {
      endTime.value = startTime.value
      startTime.value = dayjs(startTime.value).subtract(12, 'hour').format('YYYY-MM-DD HH:mm:ss')
      timeBool.value = dayjs().isAfter(dayjs(endTime.value))
    }
    getChartData()
  }

  const selectCode = ref('S11002')
  const timeBool = ref(false)
  const constantTime = ref('')
  const startTime = ref('')
  const endTime = ref('')
  const chartData = ref<any>([])
  const options = [
    {
      value: 'S11002',
      label: '进风箱压力'
    },
    {
      value: 'S11003',
      label: '机组阻力'
    },
    {
      value: 'S11004',
      label: '电能'
    }
  ]
  const getChartData = () => {
    let data = {
      firstCraftNodeName: '滤尘',
      code: [selectCode.value],
      machineDocumentIds: [machineId.value],
      start: startTime.value,
      end: endTime.value
    }
    chartData.value = []

    postGongXuXiaLiShiQuShiTu(data).then((res: any) => {
      if (res.length != 0 && res != null) {
        res[0].machineRtValue.sort((a, b) => {
          return Date.parse(a.CreationTime) - Date.parse(b.CreationTime)
        })

        res[0].machineRtValue.forEach((value) => {
          let value2 =
            value[selectCode.value] == null ? null : Math.round(value[selectCode.value] * 100) / 100
          let arr = [dayjs(value.CreationTime).format('YYYY-MM-DD HH:mm:ss'), value2]
          chartData.value.push(arr)
        })
      }
      nextTick(() => {
        handleSetVisitChart()
      })
    })
  }

  const myChart = ref()
  const handleSetVisitChart = () => {
    myChart.value = echarts.init(document.getElementById('zheXianID'))
    let option = {
      // title: {
      //   text: '趋势分析'
      // },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: [machineStr.value],
        textStyle: {
          align: 'center'
        }
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'time',
          boundaryGap: false,
          // axisLabel: {
          //   formatter: '{value}',
          //   textStyle: {
          //     color: '#333'
          //   }
          // },
          axisLine: {
            lineStyle: {
              color: '#D9D9D9'
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          },
          splitArea: {
            show: false
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '',
          axisLabel: {
            textStyle: {
              color: '#666'
            }
          },
          nameTextStyle: {
            color: '#666',
            fontSize: 12,
            lineHeight: 40
          },
          // 分割线
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#E9E9E9'
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        }
      ],

      series: [
        {
          name: machineStr.value,
          type: 'line',
          smooth: true,
          symbolSize: 8,
          yAxisIndex: 0,
          zlevel: 3,
          showSymbol: false,
          lineStyle: {
            normal: {
              color: '#8B5CFF',
              shadowBlur: 3,
              shadowColor: hexToRgba('#8B5CFF', 0.5),
              shadowOffsetY: 8
            }
          },
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: '#8B5CFF'
              },
              {
                offset: 1,
                color: '#8B5CFF'
              }
            ])
          },
          // symbol: 'circle',//数据交叉点样式
          areaStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                1,
                [
                  {
                    offset: 0,
                    color: hexToRgba('#8B5CFF', 0.3)
                  },
                  {
                    offset: 1,
                    color: hexToRgba('#8B5CFF', 0.1)
                  }
                ],
                false
              ),
              shadowColor: hexToRgba('#8B5CFF', 0.1),
              shadowBlur: 10
            }
          },
          data: chartData.value
        }
      ]
    }
    myChart.value.clear()
    myChart.value.setOption(option, true)
    window.addEventListener('resize', function () {
      myChart.value.resize()
    })
  }

  onMounted(() => {
    constantTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
    getMachineList()
  })
</script>
<style scoped lang="scss">
  .chart-card {
    margin-top: 20px;
    padding-top: 15px;
  }

  .filter-div {
    display: flex;
    justify-content: end;

    .el-button {
      margin-left: 0;
      border-radius: 0;
    }

    .type-item {
      margin-left: 20px;
    }
  }
</style>
